package ml.practicum.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
/**
 * Percist class is a utility assists in storing and loading objects
 * and allows for a clone of all serializable objects via a temporary byte buffer
 * 
 * @author Joscha
 *
 */
public class Percist {
	
	/**
	 * Loads an object from a file and catches possible errors
	 * 
	 * @param file the file pointing to a byte stream containing a serialized class
	 * @return an object loaded from the file (might need to be cast)
	 */
	public static Object load(File file){
		Object result = null;
		try{
			FileInputStream fileInputStream = new FileInputStream(file); 
			ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
			result =  objectInputStream.readObject();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(ClassNotFoundException ex)
		{
			ex.printStackTrace();
		}
		return result;
	}
	/**
	 * Stores an Object
	 * @param file the file to write the bystream to
	 * @param input the object to store
	 */
	public static void store(File file, Object input){
		try{
			file.createNewFile();
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(input);
			objectOutputStream.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	/**
	 * Clones an Object by writing it to a byte stream and create an new object by reading the byte stream
	 * @param original the object to clone
	 * @return the cloned object
	 */
	
	public static Object clone(Object original){
		Object result = null;
		ByteOutputStream bytes  = new ByteOutputStream();
		try {
			ObjectOutputStream o = new ObjectOutputStream(bytes);
			o.writeObject(original);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ByteArrayInputStream in = new ByteArrayInputStream(bytes.getBytes()); 
		try {
			try {
				result = new ObjectInputStream(in).readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}
